import React, { useEffect, useRef, useState } from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import {downloadBelowSafeLevelStock, getStockByPage, updateSafeStock} from '@/services/stock/api';
import {Button, Tag} from 'antd';

// 修改组件名
const StockControl: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [data, setData] = useState<StockVO[]>([]);
  const [total, setTotal] = useState<number>(0);

  const columns: ProColumns<StockVO>[] = [
    {
      title: '仓库编码',
      width: 120,
      dataIndex: 'warehouseCode',
      editable: false,
    },
    {
      title: '仓库名称',
      width: 120,
      dataIndex: 'warehouseName',
      editable: false,
    },
    {
      title: '货品编码',
      width: 120,
      dataIndex: 'goodsCode',
      editable: false,
    },
    {
      title: '货品名称',
      width: 120,
      dataIndex: 'goodsName',
      editable: false,
    },
    {
      title: '库存数量',
      hideInSearch: true,
      width: 120,
      editable: false,
      dataIndex: 'quantity',
    },
    {
      title: '安全库存',
      hideInSearch: true,
      width: 120,
      dataIndex: 'safeStock',
    },
    {
      title: '库存状态',
      hideInSearch: true,
      editable: false,
      width: 120,
      render: (text, record) => {
        if ((record.quantity || 0) >= (record.safeStock || 0)) {
          return <Tag color="#2db7f5">安全</Tag>;
        } else {
          return <Tag color="#f50">告警</Tag>;
        }
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            //@ts-ignore
            action?.startEditable?.(record?.id);
          }}
        >
          编辑
        </a>,
      ],
    },
  ];

  const loadData = async (params: any) => {
    const res = await getStockByPage({
      ...params,
      pageNum: currentPage,
      pageSize: 10
    });
    if (res.code != 0) {
      console.error('库存数据加载失败', res.message);
      return;
    }
    let i=1;
    const temp_ls: StockVO[]=[];
    // @ts-ignore
    for (let j = 0; j < res?.data?.records.length; j++) {
      temp_ls.push({
        "id": i+"",
        // @ts-ignore
        ...res?.data?.records[j],
      })
      i++;
    }
    setData(temp_ls);
    setTotal(res?.data?.total || 0);
  };

  useEffect(() => {
    loadData({});
  }, [currentPage]);

  return (
    <>
      <ProTable<StockVO>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        editable={{
          type: "single",
          //@ts-ignore
          onSave: (key, record, originRow, newLineConfig)=>{
            //@ts-ignore
            updateSafeStock({warehouseId: record?.warehouseId, goodsId: record?.goodsId, safeStock: record?.safeStock});
            actionRef.current?.reload();
            return 1;
          },
          actionRender: (row, config, defaultDom) => {
            return [
              defaultDom.save,
              defaultDom.cancel,
            ];
          },
        }}
        dataSource={data}
        request={async (params) => {
          await loadData(params);
          return data;
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        toolBarRender={() => [
          <Button key="download" onClick={downloadBelowSafeLevelStock}>
            下载缺货文件
          </Button>,
        ]}
        pagination={{
          pageSize: 10,
          onChange: (page) => setCurrentPage(page),
          total: total,
        }}
        headerTitle="库存查询"
      />
    </>
  );
};

// 修改导出名称
export default StockControl;
